<?php
require_once('../../carbox.php');
if(!carbox_check_session( ))
	header('Location: http://'.$_SERVER['HTTP_HOST'].'/carbox/login.php');
switch($_GET['mode']) {
	case "PROC_PAGE":
                $sql = "
			SELECT p.image, t.pos FROM
			Page p
			INNER JOIN Document AS d ON p.document_id = d.id
			INNER JOIN (SELECT p2.id, (@pos := @pos+1) AS pos FROM (SELECT @pos := 0) rn, Page p2 INNER JOIN Document AS d2 ON p2.document_id = d2.id WHERE d2.process_id = :id ORDER BY d2.type_id) AS t ON t.id = p.id
			WHERE d.process_id = :id AND IFNULL(p.number_absolute, t.pos) = :pn
                ";
		break;
	case "ONLY_DOC":
		$sql = "SELECT d.id, p.image FROM Page p INNER JOIN Document AS d ON p.document_id = d.id WHERE d.id = :id AND p.number_relative = :pn";
		break;
}
$query = end(carbox_query($sql, array(':id' => $_GET['id'], ':pn' => $_GET['page'])));
$img = (empty($query))? NULL : carbox_convert_blob_to_image($query);
if(!empty($img)) {
	$img->setImageFormat('jpeg');
	$dim = $img->getImageGeometry( );
	$r = $dim["width"]/$dim["height"];
	$w = $dim["width"]/3.0;
	$h = $w/$r;
	$img->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
	header('Content-type: image/jpeg');
	header('Content-Disposition: inline; filename="img.jpeg"');
	echo $img->getImageBlob( );
	if($_GET['mode'] == "ONLY_DOC") {
		$sql = "INSERT INTO DocumentAction (document_id, user_id, action_id, date) VALUES (:did, :uid, 2, NOW( ))";
		for($i = 0; $i < count($query); ++$i) {
			$params = array(
				':uid' => $_SESSION['uid'],
				':did' => $query[$i]['id']
			);
			carbox_query($sql, $params);
		}
	}
}
?>
